package org.groupg.practice;

import org.jgroups.*;
import org.jgroups.blocks.*;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class DistributedCache implements Receiver {
    private JChannel channel;
    private RpcDispatcher disp;
    private final Map<String, String> cache = new ConcurrentHashMap<>();

    public static void main(String[] args) throws Exception {
        new DistributedCache().start();
    }

    private void start() throws Exception {
        channel = new JChannel();
        disp = new RpcDispatcher(channel, this);
        channel.connect("CacheCluster");
        
        // 添加一些初始数据
        cache.put("key1", "value1");
        cache.put("key2", "value2");
        
        // 保持运行
        while (true) {
            Thread.sleep(10000);
        }
    }

    // 远程调用方法 - 获取值
    public String get(String key) {
        return cache.get(key);
    }

    // 远程调用方法 - 设置值
    public void put(String key, String value) {
        cache.put(key, value);
        System.out.println("Added/Updated: " + key + "=" + value);
    }

    @Override
    public void viewAccepted(View view) {
        System.out.println("Cluster members changed: " + view);
    }
}
